import { useState, useRef, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
  Send,
  Paperclip,
  Mic,
  Square,
  Command,
  CircleStop,
  Sparkles,
  Image as ImageIcon,
  FileText,
  Code,
  CornerDownLeft,
  ArrowUp,
  X,
  Smile,
  AtSign,
  Hash,
  Plus
} from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip";

interface EnhancedChatInputProps {
  inputText: string;
  isTyping: boolean;
  onInputChange: (text: string) => void;
  onSubmit: (e: React.FormEvent) => void;
  inputRef: React.RefObject<HTMLTextAreaElement>;
  onStopGeneration?: () => void;
  onFileAttach?: (files: File[]) => void;
  onVoiceRecord?: (isRecording: boolean) => void;
  placeholder?: string;
  maxLength?: number;
  disabled?: boolean;
  showAttachments?: boolean;
  showVoiceInput?: boolean;
  showEmoji?: boolean;
  showMentions?: boolean;
  attachedFiles?: File[];
  onRemoveFile?: (index: number) => void;
}

export function EnhancedChatInput({
  inputText,
  isTyping,
  onInputChange,
  onSubmit,
  inputRef,
  onStopGeneration,
  onFileAttach,
  onVoiceRecord,
  placeholder = "输入消息...",
  maxLength = 4000,
  disabled = false,
  showAttachments = true,
  showVoiceInput = true,
  showEmoji = true,
  showMentions = true,
  attachedFiles = [],
  onRemoveFile,
}: EnhancedChatInputProps) {
  const [isRecording, setIsRecording] = useState(false);
  const [showAttachmentMenu, setShowAttachmentMenu] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [textareaHeight, setTextareaHeight] = useState(56);
  const [isMobile, setIsMobile] = useState(false);
  const [isDragOver, setIsDragOver] = useState(false);
  const [cursorPosition, setCursorPosition] = useState(0);

  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const attachmentMenuRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 检测是否为移动端
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };

    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);

    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 自动调整文本框高度
  const adjustTextareaHeight = useCallback(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      const newHeight = Math.min(textareaRef.current.scrollHeight, isMobile ? 150 : 200);
      textareaRef.current.style.height = `${newHeight}px`;
      setTextareaHeight(newHeight);
    }
  }, [isMobile]);

  useEffect(() => {
    adjustTextareaHeight();
  }, [inputText, adjustTextareaHeight]);

  // 处理键盘快捷键
  const handleKeyDown = (e: React.KeyboardEvent) => {
    // 移动端不处理快捷键
    if (isMobile) return;

    // 记录光标位置
    setCursorPosition(e.currentTarget.selectionStart || 0);

    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (inputText.trim() && !isTyping && !disabled) {
        onSubmit(e);
      }
    }

    // Ctrl/Cmd + Enter 发送消息
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
      e.preventDefault();
      if (inputText.trim() && !isTyping && !disabled) {
        onSubmit(e);
      }
    }

    // @ 符号触发提及
    if (e.key === '@' && showMentions) {
      // 这里可以触发提及菜单
      console.log('Mention triggered');
    }

    // # 符号触发话题标签
    if (e.key === '#') {
      // 这里可以触发话题标签菜单
      console.log('Hashtag triggered');
    }
  };

  // 处理录音
  const toggleRecording = () => {
    const newRecordingState = !isRecording;
    setIsRecording(newRecordingState);
    onVoiceRecord?.(newRecordingState);
  };

  // 处理文件拖拽
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);

    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0 && onFileAttach) {
      onFileAttach(files);
    }
  };

  // 处理文件选择
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0 && onFileAttach) {
      onFileAttach(files);
    }
    // 重置文件输入
    e.target.value = '';
  };

  // 附件选项
  const attachmentOptions = [
    {
      icon: ImageIcon,
      label: "图片",
      type: "image",
      accept: "image/*",
      action: () => {
        if (fileInputRef.current) {
          fileInputRef.current.accept = "image/*";
          fileInputRef.current.click();
        }
      }
    },
    {
      icon: FileText,
      label: "文档",
      type: "document",
      accept: ".pdf,.doc,.docx,.txt,.md",
      action: () => {
        if (fileInputRef.current) {
          fileInputRef.current.accept = ".pdf,.doc,.docx,.txt,.md";
          fileInputRef.current.click();
        }
      }
    },
    {
      icon: Code,
      label: "代码",
      type: "code",
      accept: ".js,.ts,.py,.java,.cpp,.c,.html,.css,.json,.xml",
      action: () => {
        if (fileInputRef.current) {
          fileInputRef.current.accept = ".js,.ts,.py,.java,.cpp,.c,.html,.css,.json,.xml";
          fileInputRef.current.click();
        }
      }
    },
  ];

  // 常用表情符号
  const commonEmojis = ['😀', '😂', '🤔', '👍', '❤️', '🎉', '🔥', '💯'];

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (attachmentMenuRef.current && !attachmentMenuRef.current.contains(event.target as Node)) {
        setShowAttachmentMenu(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // 插入表情符号
  const insertEmoji = (emoji: string) => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    const start = textarea.selectionStart || 0;
    const end = textarea.selectionEnd || 0;
    const newText = inputText.slice(0, start) + emoji + inputText.slice(end);

    onInputChange(newText);

    // 恢复光标位置
    setTimeout(() => {
      textarea.focus();
      textarea.setSelectionRange(start + emoji.length, start + emoji.length);
    }, 0);

    setShowEmojiPicker(false);
  };

  const canSend = inputText.trim() && !isTyping && !disabled;
  const characterCount = inputText.length;
  const isNearLimit = characterCount > maxLength * 0.8;
  const isOverLimit = characterCount > maxLength;

  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      className="p-3 md:p-4 bg-gradient-to-t from-white/60 to-white/40 dark:from-slate-900/60 dark:to-slate-800/40 backdrop-blur-xl border-t border-white/20 dark:border-slate-700/30"
    >
      <div className="max-w-4xl mx-auto">
        {/* 附件预览 */}
        <AnimatePresence>
          {attachedFiles.length > 0 && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="mb-3 flex flex-wrap gap-2"
            >
              {attachedFiles.map((file, index) => (
                <motion.div
                  key={index}
                  initial={{ scale: 0.8, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  className="flex items-center gap-2 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg px-3 py-2"
                >
                  <FileText className="w-4 h-4 text-blue-600" />
                  <span className="text-sm text-blue-700 dark:text-blue-300 truncate max-w-32">
                    {file.name}
                  </span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => onRemoveFile?.(index)}
                    className="h-4 w-4 p-0 text-blue-600 hover:text-blue-800"
                  >
                    <X className="w-3 h-3" />
                  </Button>
                </motion.div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>

        {/* 快捷键提示和字数统计 */}
        {!isMobile && (
          <div className="flex items-center justify-between mb-2 md:mb-3 px-2">
            <div className="flex items-center gap-2 md:gap-4 text-xs text-slate-500 dark:text-slate-400">
              <div className="flex items-center gap-1">
                <Command className="w-3 h-3" />
                <CornerDownLeft className="w-3 h-3" />
                <span>发送</span>
              </div>
              <div className="flex items-center gap-1">
                <ArrowUp className="w-3 h-3" />
                <CornerDownLeft className="w-3 h-3" />
                <span>换行</span>
              </div>
            </div>

            {/* 字数统计 */}
            {characterCount > 0 && (
              <Badge
                variant={isOverLimit ? "destructive" : isNearLimit ? "secondary" : "outline"}
                className="text-xs"
              >
                {characterCount}/{maxLength}
              </Badge>
            )}
          </div>
        )}

        <form onSubmit={onSubmit} className="relative">
          {/* 附件菜单 */}
          <AnimatePresence>
            {showAttachmentMenu && (
              <motion.div
                ref={attachmentMenuRef}
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                className="absolute bottom-full left-0 md:left-4 mb-2 bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 p-2 z-50"
              >
                {/* 移动端关闭按钮 */}
                {isMobile && (
                  <button
                    type="button"
                    onClick={() => setShowAttachmentMenu(false)}
                    className="absolute top-2 right-2 p-1 rounded-full hover:bg-slate-100 dark:hover:bg-slate-700"
                  >
                    <X className="w-4 h-4 text-slate-500" />
                  </button>
                )}

                <div className="grid grid-cols-3 gap-2 mt-6 md:mt-0">
                  {attachmentOptions.map((option) => (
                    <TooltipProvider key={option.type}>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <motion.button
                            type="button"
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                            className="p-2 md:p-3 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors flex flex-col items-center"
                            onClick={() => {
                              option.action();
                              setShowAttachmentMenu(false);
                            }}
                          >
                            <option.icon className="w-5 h-5 text-slate-600 dark:text-slate-300" />
                            <span className="text-xs mt-1 text-slate-600 dark:text-slate-300">{option.label}</span>
                          </motion.button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>{option.label}</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 表情符号选择器 */}
          <AnimatePresence>
            {showEmojiPicker && (
              <motion.div
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                className="absolute bottom-full right-0 md:right-4 mb-2 bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 p-3 z-50"
              >
                <div className="grid grid-cols-4 gap-2">
                  {commonEmojis.map((emoji) => (
                    <button
                      key={emoji}
                      type="button"
                      onClick={() => insertEmoji(emoji)}
                      className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors text-lg"
                    >
                      {emoji}
                    </button>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 输入区域 */}
          <div
            className={`relative flex items-end gap-2 md:gap-3 bg-white dark:bg-slate-800 rounded-2xl border-2 transition-colors ${isDragOver
              ? 'border-blue-400 bg-blue-50 dark:bg-blue-900/20'
              : isOverLimit
                ? 'border-red-400'
                : 'border-slate-200 dark:border-slate-700'
              } shadow-lg hover:shadow-xl transition-shadow`}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
          >
            {/* 拖拽提示 */}
            {isDragOver && (
              <div className="absolute inset-0 bg-blue-50 dark:bg-blue-900/20 rounded-2xl border-2 border-dashed border-blue-400 flex items-center justify-center z-10">
                <div className="text-center">
                  <Plus className="w-8 h-8 text-blue-500 mx-auto mb-2" />
                  <p className="text-blue-600 dark:text-blue-400 font-medium">释放以添加文件</p>
                </div>
              </div>
            )}

            {/* 左侧按钮组 */}
            <div className="flex items-center gap-1 m-2">
              {/* 附件按钮 */}
              {showAttachments && (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => setShowAttachmentMenu(!showAttachmentMenu)}
                        disabled={disabled}
                        className="text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
                      >
                        <Paperclip className="w-4 h-4 md:w-5 md:h-5" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>添加附件</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              )}

              {/* 提及按钮 */}
              {showMentions && (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        disabled={disabled}
                        className="text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
                      >
                        <AtSign className="w-4 h-4 md:w-5 md:h-5" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>提及用户</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              )}
            </div>

            {/* 文本输入框 */}
            <div className="flex-1 min-w-0">
              <textarea
                ref={(el) => {
                  if (el) {
                    textareaRef.current = el;
                    if (inputRef) {
                      inputRef.current = el;
                    }
                  }
                }}
                value={inputText}
                onChange={(e) => onInputChange(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder={placeholder}
                disabled={disabled || isTyping}
                maxLength={maxLength}
                className="w-full px-2 py-2 md:px-2 md:py-3 bg-transparent text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 resize-none outline-none text-sm md:text-base leading-relaxed"
                style={{ height: `${textareaHeight}px`, maxHeight: isMobile ? '150px' : '200px' }}
                rows={1}
              />
            </div>

            {/* 右侧按钮组 */}
            <div className="flex items-center gap-1 md:gap-2 m-2">
              {/* 表情符号按钮 */}
              {showEmoji && (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                        disabled={disabled}
                        className="text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
                      >
                        <Smile className="w-4 h-4 md:w-5 md:h-5" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>添加表情</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              )}

              {/* 录音按钮 */}
              {showVoiceInput && (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={toggleRecording}
                        disabled={disabled}
                        className={`text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 ${isRecording ? 'text-red-500 hover:text-red-600' : ''
                          }`}
                      >
                        <motion.div
                          animate={isRecording ? { scale: [1, 1.1, 1] } : {}}
                          transition={{ duration: 1, repeat: isRecording ? Infinity : 0 }}
                        >
                          {isRecording ? (
                            <Square className="w-4 h-4 md:w-5 md:h-5" />
                          ) : (
                            <Mic className="w-4 h-4 md:w-5 md:h-5" />
                          )}
                        </motion.div>
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>{isRecording ? '停止录音' : '开始录音'}</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              )}

              {/* 发送/停止按钮 */}
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      type={isTyping ? "button" : "submit"}
                      disabled={(!canSend && !isTyping) || isRecording || isOverLimit}
                      onClick={isTyping ? onStopGeneration : undefined}
                      className={`${isTyping
                        ? 'bg-red-500 hover:bg-red-600 text-white'
                        : 'bg-blue-500 hover:bg-blue-600 text-white'
                        } shadow-lg hover:shadow-xl transition-all h-8 w-8 md:h-10 md:w-10 p-0`}
                    >
                      <motion.div
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                      >
                        {isTyping ? (
                          <CircleStop className="w-4 h-4 md:w-5 md:h-5" />
                        ) : (
                          <Send className="w-4 h-4 md:w-5 md:h-5" />
                        )}
                      </motion.div>
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>{isTyping ? '停止生成' : '发送消息'}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </div>

          {/* 隐藏的文件输入 */}
          <input
            ref={fileInputRef}
            type="file"
            multiple
            onChange={handleFileSelect}
            className="hidden"
          />

          {/* AI能力提示 - 仅桌面端显示 */}
          {!isMobile && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="mt-2 md:mt-3 flex items-center justify-center gap-1 md:gap-2 text-xs text-slate-500 dark:text-slate-400"
            >
              <Sparkles className="w-3 h-3" />
              <span>支持代码高亮 • 表格解析 • 图像识别 • 文档处理 • 语音输入</span>
            </motion.div>
          )}
        </form>
      </div>
    </motion.div>
  );
}
